<?php
//+-----------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+-----------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+-----------------------------------------------------------
//| 
//+-----------------------------------------------------------


namespace app\common\traits;

use app\common\response\HttpCode;
use think\exception\HttpResponseException;
use think\Response;

/**
 * 跳转辅助
 * @package app\common\traits
 */
trait Jump
{
    public function success($msg='',$url=null,$wait=3,$data=[],$header=[]){
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app->route->buildUrl($url);
        }

        $result = [
            'code' => HttpCode::CODE_SUCCESS,
            'msg' => $msg,
            'data' => $data,
            'wait' => $wait,
            'url' => $url
        ];

        $type = ($this->getResponseType());
        if($type == 'view'){
            $response = Response::create(app()->config->get('app.dispatch_tmpl'), $type)->header($header)->assign($result);
        }else{
            $response = Response::create($result, $type)->header($header);
        }
        throw new HttpResponseException($response);
    }

    public function error($msg='',$url=null,$wait=3,$data=[],$header=[]){
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url :  $this->app->route->buildUrl($url);
        }

        $content = [
            'code' => HttpCode::CODE_ERROR,
            'msg' => $msg,
            'data' => $data,
            'wait' => $wait,
            'url' => $url
        ];

        $type = ($this->getResponseType());
        if($type == 'view'){
            $response = Response::create(app()->config->get('app.dispatch_tmpl'), $type)->header($header)->assign($content);
        }else{
            $response = Response::create($content, $type)->header($header);
        }
        throw new HttpResponseException($response);
    }

    private function getResponseType(){
        return $this->request->isJson() || $this->request->isAjax() ? 'json' : 'view';
    }
}